package cn.gaily.eduservice.service.impl;

import cn.gaily.eduservice.entity.EduSubject;
import cn.gaily.eduservice.entity.excel.SubjectData;
import cn.gaily.eduservice.entity.tree.OneSubject;
import cn.gaily.eduservice.entity.tree.TwoSubject;
import cn.gaily.eduservice.listener.SubjectExcelListener;
import cn.gaily.eduservice.mapper.EduSubjectMapper;
import cn.gaily.eduservice.service.EduSubjectService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author xuchengwei
 * @since 2021-06-30
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try{
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        //查询所有一级分类
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<EduSubject> oneList = baseMapper.selectList(wrapper);
        //查询二级分类
        QueryWrapper<EduSubject> wrapper2 = new QueryWrapper<>();
        wrapper2.ne("parent_id",0);//ne代表不等于
        List<EduSubject> twoList = baseMapper.selectList(wrapper2);
        //创建list集合封装
        List<OneSubject> allList = new ArrayList<>();
        //封装一级分类
        for (int i = 0; i < oneList.size(); i++) {
            EduSubject eduSubject1 = oneList.get(i);
            OneSubject oneSubject = new OneSubject();
            //直接复制一个对象中的值到另一个对象，前提是属性名相等
            BeanUtils.copyProperties(eduSubject1,oneSubject);
            ArrayList<TwoSubject> secondList = new ArrayList<>();
            for (int j = 0; j < twoList.size(); j++) {
                EduSubject eduSubject2 = twoList.get(j);
                TwoSubject twoSubject = new TwoSubject();
                BeanUtils.copyProperties(eduSubject2,twoSubject);
                if(oneSubject.getId().equals(eduSubject2.getParentId()))
                secondList.add(twoSubject);
            }
            oneSubject.setChildren(secondList);
            allList.add(oneSubject);
        }
        //封装二级分类

        return allList;
    }
}
